﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using ecdl.demo.model.expression;
using ecdl.demo.model;
using System.Xml.Serialization;

using Ninject;

namespace ecdl.demo.model.expression {
    public class IsWriteProtectedCondition : Expression {

        private IVolumeProvider volumeProvider;

        [Inject]
        public IsWriteProtectedCondition(IVolumeProvider volumeProvider) {
            this.volumeProvider = volumeProvider;
        }

        private string fileName;

        public string FileName {
            get { return fileName; }
            set {
                string path = volumeProvider.GetFullPath(value);
                fileName = path;
            }
        }

        /* <FileIsWriteProtected fileName="Schmemse.txt" /> */
        public override ExpressionState Evaluate(ExpressionContext context) {

            LeafExpressionState state = new LeafExpressionState(this);
            FileInfo fInfo = new FileInfo(fileName);

            state.IsOk = fInfo.IsReadOnly;
            SetCause(state);

            return state;
        }

        private void SetCause(LeafExpressionState state) {
            string positive = String.Format("Die Datei {0} muss schreibgeschützt sein.", FileName);
            string negative = String.Format("Die Datei {0} darf nicht schreibgeschützt sein.", FileName);
            state.SetCause(positive, negative);
        }
    }

    public class IsWriteProtectedConditionDTO : ExpressionDTO {
        [XmlAttribute("fileName")]
        public string FileName { get; set; }

        public override Expression ToModel(persistence.ModelFactory factory) {
            IsWriteProtectedCondition condition = factory.CreateModel<IsWriteProtectedCondition>();
            condition.FileName = FileName;
            return condition;
        }
    }

}
